<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2020/9/3
 * Time: 11:19
 */

namespace app\admin\model;
use think\Model;

class Article extends Model
{
    protected static function init()
    {
        #新增文章前先新增图片
        Article::event('before_insert',function($data){
            if($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public/static' . DS . 'uploads');
                if($info){
                    $thumb = 'http://www.qiyefour.com/' . 'static' . DS . 'uploads' . '/' . $info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });

        #更新文章的时候, 删除目录下旧图片
        Article::event('before_update', function($data){
            if($_FILES['thumb']['tmp_name']){
                $arts = Article::find($data->id);
                $thumbpath = $_SERVER['DOCUMENT_ROOT'] . $arts['thumb'];
                if(file_exists($thumbpath)){
                    @unlink($thumbpath);
                }
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public/static' . DS . 'uploads');
                if($info){
                    $thumb = '/' . 'static' . DS  . 'uploads' . '/'  . $info->getSaveName();
                    $data['thumb'] = $thumb;
                }

            }
        });

        #删除文章之前删除该文章的图片
        Article::event('before_delete', function($data){
            $arts = Article::find($data->id);
            $thumbpath = $_SERVER['DOCUMENT_ROOT'] . $arts['thumb'];
            if(file_exists($thumbpath)){
                @unlink($thumbpath);
            }
        });



    }





}